package face.yuque;

import java.util.Arrays;

/**
 * @author spf
 * @date 2024/12/12
 * @time 20:57
 */

//两数之和
//方法三：二分查找
public class TwoSum3 {

    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6};
        int target = 10;
        System.out.println(Arrays.toString(twoSum(nums, target)));
    }

    private static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            int l = i, r = nums.length - 1;
            while (l <= r) {
                int mid = (l + r) / 2;
                if (nums[mid] == target - nums[i]) {
                    return new int[]{i, mid};
                } else if (nums[mid] < target - nums[i]) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
        }
        return new int[]{0};
    }

}
